package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.adapter.AddressAdapter;
import com.century.sjt.entity.Address;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 炳基 on 2016/5/25.
 * 地址管理：
 */
public class AddressManageActivity extends BaseActivity{
    private SjtTitleBar titleBar;
    private RequestQueue mQueue;

    private List<Address> mDatalist;
    private ListView listAddress;
    private AddressAdapter adapter;
    private LinearLayout layout_Add;

    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Handler mHandler;
    private Boolean isDataChangeOk = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        mQueue = Volley.newRequestQueue(this);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
//                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk = true;
                        mDatalist.clear();
                        getAddress();
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            getAddress();
                        }
                        break;
                    case 4:
                        mDatalist.clear();
                        getAddress();
                        break;

                }
            }
        };
        initView();
        initEvent();
        initData();
    }

    private void getAddress() {
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.queryReceiver, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取地址", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        if (res.getJSONArray("data").length() == 0) {
//                            TipUtil.showToast("", AddressManageActivity.this);
                            showAppayRes();
                        } else {
                            mDatalist.clear();
                            JSONArray data = res.getJSONArray("data");
                            for (int i = 0; i < data.length(); i++) {

                                JSONObject aData = (JSONObject) data.get(i);
//
                                Address address = new Address();
                                address.setSysId(aData.getString("sysId"));
                                address.setAddress(aData.getString("address"));
                                address.setAreaName(aData.getString("areaName"));
                                address.setConsignee(aData.getString("consignee"));
                                address.setIsDefault(aData.getString("isDefault"));
                                address.setPhone(aData.getString("phone"));
                                address.setIpCode(aData.getString("zipCode"));
//                            address.setArexz(aData.getString("areaName"));
                                address.setUserId(aData.getString("userId"));
                                mDatalist.add(address);
                            }

                        }
                    } else {//失败
                        TipUtil.showToast(message, AddressManageActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), AddressManageActivity.this, 1);
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), AddressManageActivity.this, 1);
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
//                map.put("paging.currentPage",String.valueOf(iCurrPage));//当前页码
//                map.put("paging.pageSize",Constant.PAGESIZE+" ");//查询条数

                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getAddress();
    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        layout_Add = (LinearLayout) findViewById(R.id.layout_add_address);
        mDatalist = new ArrayList<>();
        listAddress = (ListView) findViewById(R.id.list_address);
        adapter = new AddressAdapter(AddressManageActivity.this, mDatalist, mQueue);
        listAddress.setAdapter(adapter);
        listAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent resultInten = new Intent();
                Gson gson = new Gson();
                resultInten.putExtra("result", gson.toJson(adapter.getItem(position)));
                setResult(RESULT_OK,resultInten);
                finish();
            }
        });
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.activity_list_refesh);
        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

    }

    @Override
    protected void initEvent() {
        //       标题栏
        titleBar.setTitle(getResources().getString(R.string.tab_addrss_manage));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    finish();
            }
        });
//        layout_Add.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(AddressManageActivity.this, AddressAddActivity.class);
//                startActivity(intent);
//            }
//        });
        titleBar.setRightIconResourc(getResources().getString(R.string.btn_add_address));
        titleBar.setRightIconSize();

        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(AddressManageActivity.this, AddressAddActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void initData() {

    }

    public void showAppayRes() {
        //询问是否取消
        AlertDialog.Builder builder = new AlertDialog.Builder(AddressManageActivity.this);
        builder.setTitle(getResources().getString(R.string.text_prompt));
        builder.setMessage(getResources().getString(R.string.error_no_one_address));
        builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent();
                intent.putExtra("Type", "3");
                intent.setClass(AddressManageActivity.this, AddressAddActivity.class);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

}
